/**
 * @file bull_hal_net_ntp.c
 * @brief 
 * @author yejing (yejh@gongniu.cn)
 * @version 1.0
 * @date 2024-07-25
 * 
 * Copyright 2024-2025 GongNiu Inc. All Rights Reserved.
 * 
 */
#include "bull_hal_net_ntp.h"
#include "lwip/apps/sntp.h"
#include "esp_netif_sntp.h"

esp_sntp_config_t ntp_config = {

    .smooth_sync = false,                       \
    .server_from_dhcp = false,                  \
    .wait_for_sync = true,                      \
    .start = true,                              \
    .sync_cb = NULL,                            \
    .renew_servers_after_new_IP = false,        \
    .ip_event_to_renew = IP_EVENT_STA_GOT_IP,   \
    .index_of_first_server = 0,                 \
};


/**
 * @brief 设置NTP工作模式
 * 
 * @param operating_mode 
 */
void bull_hal_net_ntp_setoperatingmode( uint8_t operating_mode )
{
    sntp_setoperatingmode( operating_mode );
}


/**
 * @brief 设置NTP同步间隔
 * 
 * @param idx 设置序列号
 * @param server 服务器名称
 */
void bull_hal_net_ntp_set_setservername( uint8_t idx, const char *server)
{
    if ( idx < CONFIG_LWIP_SNTP_MAX_SERVERS ){

        ntp_config.servers[ idx ] = server;

        ntp_config.num_of_servers = idx + 1;
    }
    
}


/**
 * @brief Init and start SNTP service 
 * 
 */
void bull_hal_net_ntp_init( void )
{
    // esp_sntp_init();
    esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG("ntp3.aliyun.com");
    esp_netif_sntp_init( &config );
}

/**
 * @brief Stops SNTP service
 * 
 */
void bull_hal_net_ntp_stop( void )
{
    esp_sntp_stop();
}

/**
 * @brief Restart SNTP
 * 
 * @return True  - Restart
 *         False - SNTP was not initialized yet
 */
bool bull_hal_net_ntp_start( void )
{
    return esp_netif_sntp_start();
}

/**
 * @brief 获取当前ntp状态
 * 
 * @return bull_sntp_sync_status_t 
 */
int bull_ntp_get_sync_status( void )
{
    // return sntp_get_sync_status();

    // wait for time to be set
    time_t now = 0;
    struct tm timeinfo = { 0 };
    int retry = 0;
    const int retry_count = 15;
    while (esp_netif_sntp_sync_wait(2000 / portTICK_PERIOD_MS) == ESP_ERR_TIMEOUT && ++retry < retry_count) {
        // ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
    }
    time(&now);
    localtime_r(&now, &timeinfo);

    // return BULL_SNTP_SYNC_STATUS_RESET;
    return 0;

}